package com.guaju.yueshangLife.activity.mine;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.setting.MyInfoActivity;
import com.guaju.yueshangLife.adapter.ServiceAdapter;
import com.guaju.yueshangLife.base.BaseActivity;
import com.guaju.yueshangLife.bean.ServiceMsg;
import com.guaju.yueshangLife.databinding.ActivityServiceBinding;
import com.guaju.yueshangLife.emoji.EmojiBean;
import com.guaju.yueshangLife.emoji.EmojiDao;
import com.guaju.yueshangLife.emoji.ExpressionAdapter;
import com.guaju.yueshangLife.emoji.ItemChildClickListener;
import com.guaju.yueshangLife.utils.KeybordUtil;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.SoftKeyBoardListener;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMCustomElem;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMValueCallBack;

import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class ServiceActivity extends BaseActivity {

    private static final int REQUEST_PHOTO_PERMISSION = 1000;
    private static final int REQUEST_SELECT_IMAGES_CODE = 1100;
    private static final int REQUEST_CODE_FOR_ORDER = 1200;
    ActivityServiceBinding binding;
    private ServiceAdapter serviceAdapter;
    private ArrayList<ServiceMsg> serviceMsgs;
    private ExpressionAdapter adapter;
    private List<EmojiBean> emojiBeens;
    private boolean isKeyBoardShowing = false;
    private static final int REQUEST_TAKE_PHOTO_PERMISSION = 1001;

    @Override
    protected void loadViewLayout() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_service);
    }

    @Override
    protected void bindViews() {
        setEmoji();
    }

    private void setEmoji() {

        emojiBeens = new ArrayList<>();
        emojiBeens = EmojiDao.getInstance().getEmojiBean();
        GridLayoutManager manager = new GridLayoutManager(this, 5, GridLayoutManager.HORIZONTAL, false);
        binding.emojiRv.setLayoutManager(manager);
        adapter = new ExpressionAdapter(emojiBeens, this);
        binding.emojiRv.setAdapter(adapter);

        adapter.setItemChildClickListener(new ItemChildClickListener() {
            @Override
            public void onChildClick(int position) {
                binding.etMsg.append(adapter.getItem(position).getEmojiString());
            }
        });

        binding.ivEmoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.llEmoji.getVisibility() == View.VISIBLE) {
                    binding.llEmoji.setVisibility(View.GONE);
                } else {
                    if (isKeyBoardShowing) {
                        KeybordUtil.hideKeyboard(ServiceActivity.this);
                    }
                    if (binding.llAdd.getVisibility() == View.VISIBLE) {
                        binding.llAdd.setVisibility(View.GONE);
                    }
                    binding.llEmoji.setVisibility(View.VISIBLE);
                    binding.llEmoji.setVisibility(View.VISIBLE);
                }

            }
        });
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        serviceMsgs = new ArrayList<>();
        serviceMsgs.add(new ServiceMsg(ServiceAdapter.SENDER_SERVICE, ServiceAdapter.TYPE_TEXT, "您好,请问需要什么服务？", ""));
        serviceMsgs.add(new ServiceMsg(ServiceAdapter.SENDER_MINE, ServiceAdapter.TYPE_TEXT, "你好，我想咨询一下", ""));
        serviceMsgs.add(new ServiceMsg(ServiceAdapter.SENDER_SERVICE, ServiceAdapter.TYPE_TEXT, "您好,请问需要什么服务？", ""));
        serviceMsgs.add(new ServiceMsg(ServiceAdapter.SENDER_MINE, ServiceAdapter.TYPE_TEXT, "我想咨询一下这个衣服还有货吗", ""));
        serviceMsgs.add(new ServiceMsg(ServiceAdapter.SENDER_SERVICE, ServiceAdapter.TYPE_TEXT, "您好，在吗", ""));
        serviceAdapter = new ServiceAdapter(ServiceActivity.this, serviceMsgs);
        binding.recyclerView.setAdapter(serviceAdapter);
    }

    @Override
    protected void setListener() {


        binding.etMsg.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String msg = binding.etMsg.getText().toString().trim();
                    sendMessage(msg);
                    return true;
                }
                return false;
            }
        });
        binding.tvSendEmoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = binding.etMsg.getText().toString().trim();
                sendMessage(msg);
            }
        });
        setupSoftKeyBoardHeightSystem();

        binding.llMsgSelectPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PermissionGen.with(ServiceActivity.this)
                        .addRequestCode(REQUEST_PHOTO_PERMISSION)
                        .permissions(
                                Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request();

            }
        });

        binding.llMsgTakephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionGen.with(ServiceActivity.this)
                        .addRequestCode(REQUEST_TAKE_PHOTO_PERMISSION)
                        .permissions(
                                Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request();
            }
        });
        binding.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.llAdd.getVisibility() == View.GONE) {
                    if (isKeyBoardShowing) {
                        KeybordUtil.hideKeyboard(ServiceActivity.this);
                    }
                    if (binding.llEmoji.getVisibility() == View.VISIBLE) {
                        binding.llEmoji.setVisibility(View.GONE);
                    }

                    binding.llAdd.setVisibility(View.VISIBLE);
                }
            }
        });
        binding.llMsgMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ServiceActivity.this, SelectOrderListActivity.class);
                startActivityForResult(intent, REQUEST_CODE_FOR_ORDER);
            }
        });

        binding.ivVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ivKeyboard.setVisibility(View.VISIBLE);
                binding.ivVoice.setVisibility(View.GONE);
            }
        });
        binding.ivKeyboard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ivKeyboard.setVisibility(View.GONE);
                binding.ivVoice.setVisibility(View.VISIBLE);
            }
        });

    }

    private void sendMessage(final String text) {
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(mContext, "请说点什么吧~~~", Toast.LENGTH_SHORT).show();
            return;
        }

        if (serviceAdapter != null) {
            ServiceMsg liveMsgBean = new ServiceMsg(ServiceAdapter.SENDER_MINE, ServiceAdapter.TYPE_TEXT, text, "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1562307125&di=a21f00f07bbc7a2dce8862a938d4e161&src=http://img.tupianzj.com/uploads/allimg/20170817/0H4xwuLi39450.jpeg");
            serviceMsgs.add(liveMsgBean);
            serviceAdapter.notifyDataSetChanged();
            serviceAdapter.notifyItemInserted(serviceMsgs.size());
            /**
             * 如果查看了某条信息，这个时候不自动滚到底部位置
             */
            binding.etMsg.setText("");
        }

        realSendMsg(text);
    }

    private void realSendMsg(String text) {
        TIMMessage message = new TIMMessage();
        try {
            CommonJson<UserInfo> txtHeadMsg = new CommonJson<UserInfo>();
            txtHeadMsg.cmd = "CustomTextMsg";
            txtHeadMsg.data = new UserInfo(PreferenceUtil.getUserName(), PreferenceUtil.getAvatar(), "1");
            String strCmdMsg = new Gson().toJson(txtHeadMsg, new TypeToken<CommonJson<UserInfo>>() {
            }.getType());

            TIMCustomElem customElem = new TIMCustomElem();
            customElem.setData(strCmdMsg.getBytes("UTF-8"));

            TIMTextElem textElem = new TIMTextElem();
            textElem.setText(text);

            message.addElement(customElem);
            message.addElement(textElem);
        } catch (Exception e) {
//            Toast.makeText(this, "发送群消息失败", Toast.LENGTH_SHORT).show();
            return;
        }


        TIMConversation timConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, "对方账号");
        timConversation.sendMessage(message, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess(TIMMessage timMessage) {


            }
        });
    }

    private static final class UserInfo {
        String nickName;
        String headPic;
        String role;

        public UserInfo(String nickName, String headPic, String role) {
            this.nickName = nickName;
            this.headPic = headPic;
            this.role = role;
        }
    }

    private static class CommonJson<T> {
        String cmd;
        T data;
    }


    private void setupSoftKeyBoardHeightSystem() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                /**
                 * 软键盘出来的时候
                 */
                isKeyBoardShowing = true;
                if (binding.llEmoji.getVisibility() == View.VISIBLE) {
                    binding.llEmoji.setVisibility(View.GONE);
                }

            }

            @Override
            public void keyBoardHide(int height) {
                isKeyBoardShowing = false;
                /**
                 * 软键盘下去的时候
                 */
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionGen.onRequestPermissionsResult(ServiceActivity.this, requestCode, permissions, grantResults);
    }

    @PermissionFail(requestCode = REQUEST_PHOTO_PERMISSION)
    public void doFailSomething() {
        Toast.makeText(this, "未开启访问相册权限", Toast.LENGTH_SHORT).show();
    }

    @PermissionSuccess(requestCode = REQUEST_PHOTO_PERMISSION)
    public void doSuccessThing() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);
        startActivityForResult(intent, REQUEST_SELECT_IMAGES_CODE);
    }


    @PermissionFail(requestCode = REQUEST_TAKE_PHOTO_PERMISSION)
    public void doTakeSomething() {
        Toast.makeText(this, "未开启访问相册权限", Toast.LENGTH_SHORT).show();
    }

    @PermissionSuccess(requestCode = REQUEST_TAKE_PHOTO_PERMISSION)
    public void doTakeSuccessThing() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
        startActivityForResult(intent, REQUEST_SELECT_IMAGES_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (requestCode == REQUEST_SELECT_IMAGES_CODE) {
                if (data != null) {
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    ImageItem imageItem = images.get(0);
//                    binding.avatar.setImageURI(imageItem.path);

                    /**
                     * 此时先将图片传到云服务器，然后再发送出去
                     */
//                    new ServiceMsg(ServiceAdapter.SENDER_MINE,)
                    ToastUtils.showLongToast(ServiceActivity.this, "图片选择成功");
//                    上传至服务器
                } else {
                    ToastUtils.showLongToast(ServiceActivity.this, "图片选择失败");
                }
            }
        }
    }
}